package com.neucollege.system.interceptor;

import com.neucollege.system.constant.MessageConstant;
import com.neucollege.system.context.UserContext;
import com.neucollege.system.domain.pojo.Supervisor;
import com.neucollege.system.exception.UserNotLoginExecption;
import com.neucollege.system.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.Objects;

@Component
@RequiredArgsConstructor
public class NEPSInterceptor implements HandlerInterceptor {
    private final JwtUtils jwtUtils;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if(!Objects.nonNull(token)){
            throw new UserNotLoginExecption(MessageConstant.USER_NOT_LOGIN);
        }
        Supervisor supervisor = jwtUtils.parseSupervisor(token);
        UserContext.saveUser(supervisor);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContext.remove();
    }
}
